package yf.mall.controller;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.yf.annotation.LoginUserId;
import com.yf.response.RRException;
import com.yf.utils.ShiroUtils;
import yf.mall.common.Const;
import yf.mall.dao.PriceDao;
import yf.mall.dao.SysUserUserDao;
import yf.mall.entity.*;
import yf.mall.enums.AccountTypeEnum;
import yf.mall.enums.MallActRewardTypeEnum;
import yf.mall.enums.MallActStatusEnum;
import yf.mall.enums.MallGoodsShelfEnum;
import yf.mall.service.*;
import yf.mall.vo.ActGoodsVo;
import yf.mall.vo.PriceVo;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yf.annotation.SysLog;

import com.yf.consts.DaoConst;
import com.yf.response.R;


/**
 * 产品Controller
 *
 * @author hxf
 * @email 505860922@qq.com
 * @date Mon Aug 05 15:29:09 CST 2019
 */
@RestController
@RequestMapping("/mallGoods")
public class MallGoodsController {
    @Autowired
    private MallGoodsService mallGoodsService;

    @Autowired
    private PriceService priceService;

    @Autowired
    private SysUserUserDao sysUserUserDao;
    @Autowired
    ShopService shopService;
    @Autowired
    SysUsersService sysUsersService;
    @Autowired
    LevelService levelService;

    /**
     * 列表产品
     */
    @RequestMapping("/list")
    @RequiresPermissions("mall:goods:list")
    public R list(@RequestParam Map<String, Object> params) {
        Long sysUserId = ShiroUtils.getUserId();
        UserEntity userEntity = this.sysUserUserDao.findBySysUserId(sysUserId);
        Long userId = null;
        if (userEntity != null) {
            params.put("userId", userEntity.getId());
            userId = userEntity.getId();
        }
        ShopEntity shop = null;
        if (params.get("shopName") != null && !"".equals(params.get("shopName"))) {
            shop = shopService.findByName((String) params.get("shopName"));
            if (shop != null) {
                params.put("userId", shop.getUserId());
                userId = shop.getUserId();
            }
        }
        PageHelper.startPage(DaoConst.getPage(params), DaoConst.getLIMIT(params)).setOrderBy(DaoConst.getOrder(params));
        List<MallGoodsEntity> mallGoodsList = null;
        //根据分类查询 que
        if (params.get("type") != null && !"".equals(params.get("type"))) {
            Integer type = Integer.parseInt((String) params.get("type"));
            String name = "";
            if (params.get("name") != null) {
                name = (String) params.get("name");
            }
            Integer shelf = null;
            if (params.get("shelf") != null && !"".equals(params.get("shelf"))) {
                shelf = Integer.parseInt((String) params.get("shelf"));
            }
            Integer saleType = null;
            if (params.get("saleType") != null && !"".equals(params.get("saleType"))) {
                saleType = Integer.parseInt((String) params.get("saleType"));
            }
            mallGoodsList = mallGoodsService.findByTypeAndGoodsNameAndShelf(type, name, shelf, userId, saleType);
        } else {
            mallGoodsList = mallGoodsService.queryList(params);
        }
        //获取所属店铺
        if (mallGoodsList != null && mallGoodsList.size() > 0) {
            for (MallGoodsEntity mallGoodsEntity : mallGoodsList) {
                if (mallGoodsEntity.getUserId() != null) {
                    ShopEntity shopEntity = shopService.findByUserId(mallGoodsEntity.getUserId());
                    if (shopEntity != null) {
                        mallGoodsEntity.setShopEntity(shopEntity);
                    }
                }
            }
        }
        Long id = ShiroUtils.getUserId();
        userId = sysUsersService.findBySysUserId(id);
        List<Long> roleId = sysUsersService.findRole(sysUserId);
        List<MallGoodsEntity> goodsEntities = mallGoodsService.queryList(null);

        List<LevelEntity> levelEntities = levelService.queryList(null);
        return R.ok(new PageInfo(mallGoodsList))
                .putExtra("userId", userId)
                .putExtra("roleId", roleId).putExtra("goodsList", goodsEntities)
                .putExtra("levelList", levelEntities);
    }

    @RequestMapping("/goodsList")
    public R goodsList() {
        Map<String, Object> params = new HashMap<>();
        Long sysUserId = ShiroUtils.getUserId();
        UserEntity userEntity = this.sysUserUserDao.findBySysUserId(sysUserId);
        if (userEntity != null) {
            params.put("userId", userEntity.getId());
        }
        List<MallGoodsEntity> mallGoodsEntities = mallGoodsService.queryList(params);
        return R.ok(mallGoodsEntities);
    }

    @Autowired
    private SaleTypeInfoService saleTypeInfoService;
    @Autowired
    private MallActService mallActService;

    @Autowired
    private UserService userService;
    /**
     * 查看产品
     */
    @SysLog("查看产品")
    @RequestMapping("/info/{id}")
    @RequiresPermissions("mall:goods:info")
    public R info(@PathVariable("id") Long id) {
        MallGoodsEntity mallGoods = mallGoodsService.getWithSku(id);
        //获取价格
        List<PriceVo> priceVos = priceService.findByGoodsIdAndCode(id,null);
        List<PriceEntity> priceEntities = new ArrayList<>();
        priceVos.forEach(priceVo -> {
            if(priceVo.getLevel()!=null) {
                priceVo.getPrice().setLevelName(priceVo.getLevel().getName());
                priceEntities.add(priceVo.getPrice());
            }
        });
        List<List> pricesList = priceEntities.stream().collect(Collectors.groupingBy(PriceEntity::getVipCode,Collectors.toList())).values().stream().collect(Collectors.toList());
        mallGoods.setPrices(priceEntities);
        SaleTypeInfoEntity saleTypeInfoEntity = saleTypeInfoService.findByGoodsId(id);
        List typesResult = mallTypeService.findByGoodsId(id);
        //获取产品分类资质
        GoodsQualificationEntity goodsQualificationEntity = goodsQualificationService.findByGoodsId(mallGoods.getId());
        List<MallGoodsEntity> goodsEntityList = mallGoodsService.findNoGoodId(id);
        MallActEntity act = mallActService.findByGoodsIdAndstatus(id, MallActStatusEnum.OPEN.getIndex());
        return R.ok(mallGoods).putExtra("saleTypeInfoEntity", saleTypeInfoEntity)
                .putExtra("types", typesResult)
                .putExtra("goodsQualificationEntity", goodsQualificationEntity)
                .putExtra("act", act).putExtra("pricesList",pricesList)
                .putExtra("goodsEntityList", goodsEntityList);
    }

    @Autowired
    private PriceDao priceDao;

    @Autowired
    private MallTypeService mallTypeService;
    @Autowired
    private GoodsQualificationService goodsQualificationService;

    /**
     * 保存产品
     */
    @SysLog("保存产品")
    @RequestMapping("/save")
    @RequiresPermissions("mall:goods:save")
    public R save(@RequestBody ActGoodsVo actGoodsVo) {
        Long sys_userId = ShiroUtils.getUserId();
        //获取绑定的用户id
        Long userId = sysUsersService.findBySysUserId(sys_userId);
        //不是公司管理员 不能设置上架
        if (userId != null) {
            //如果是上架 则改为待审核
            if (actGoodsVo.getGoods().getShelf() == null) {
                actGoodsVo.getGoods().setShelf(MallGoodsShelfEnum.DOWN.getIndex());
            }
            if (actGoodsVo.getGoods().getShelf() == MallGoodsShelfEnum.ON.getIndex()) {
                actGoodsVo.getGoods().setShelf(MallGoodsShelfEnum.AUDIT.getIndex());
            }
            actGoodsVo.getGoods().setUserId(userId);
        }
        mallGoodsService.merge(actGoodsVo,userId);

        if (userId != null) {
            ShopEntity shopEntity = shopService.findByUserId(userId);
            actGoodsVo.getGoods().setShopEntity(shopEntity);
        }
        return R.ok(actGoodsVo.getGoods());
    }


    /**
     * 修改产品
     */
    @SysLog("修改产品")
    @RequestMapping("/update")
    @RequiresPermissions("mall:goods:update")
    public R update(@RequestBody ActGoodsVo actGoodsVo) {
        if (actGoodsVo.getGoods() == null) {
            throw new RRException("产品不存在");
        }
        Long sys_userId = ShiroUtils.getUserId();
        //获取绑定的用户id
        Long userId = sysUsersService.findBySysUserId(sys_userId);
        //不是公司管理员 不能设置上架
        if (userId != null) {
            //如果是上架并且是调整 则改为待审核
            if (actGoodsVo.getGoods().getShelf() == MallGoodsShelfEnum.ON.getIndex() && !actGoodsVo.getAdjustFlag()) {
                actGoodsVo.getGoods().setShelf(MallGoodsShelfEnum.AUDIT.getIndex());
            }
        }
        mallGoodsService.merge(actGoodsVo,userId);

        //查找所属店铺
        if (actGoodsVo.getGoods().getUserId() != null) {
            ShopEntity shopEntity = shopService.findByUserId(actGoodsVo.getGoods().getUserId());
            actGoodsVo.getGoods().setShopEntity(shopEntity);
        }
        return R.ok(actGoodsVo.getGoods());
    }

    @Autowired
    GoodsQualificationService getGoodsQualificationService;

    /**
     * 删除产品
     */
    @SysLog("删除产品")
    @RequestMapping("/delete")
    @RequiresPermissions("mall:goods:delete")
    public R delete(Long[] ids) {
        mallGoodsService.delByGoodsId(ids);
        return R.ok();
    }

    /**
     * 所有产品
     */
    @SysLog("所有产品")
    @RequestMapping("/queryAll")
    public R queryAll(Map<String, Object> params) {
        Long sysUserId = ShiroUtils.getUserId();
        UserEntity userEntity = this.sysUserUserDao.findBySysUserId(sysUserId);
        if (userEntity != null) {
            params.put("userId", userEntity.getId());
        }
        List<MallGoodsEntity> mallGoodsList = mallGoodsService.queryList(params);

        return R.ok(mallGoodsList);
    }

    /**
     @ModelAttribute public SearchParam<MallGoodsEntity> searchParam(SearchParam<MallGoodsEntity> params, MallGoodsEntity mallGoods) {
     if (mallGoods != null) {
     params.setEntity(mallGoods);
     }

     return params;
     }
     **/
    /***********自定义开始***********/

    @RequestMapping("/stock")
    public R updateStock(StockRecordEntity stockRecordEntity) {
        MallGoodsEntity mallGoodsEntity = mallGoodsService.updateStock(stockRecordEntity);
        return R.ok(mallGoodsEntity);
    }

    @RequestMapping("/findByUserId/{shopId}")
    public R findByUserId(@PathVariable("shopId") Long shopId) {
        Long userId = null;
        if (shopId != null && !shopId.equals(Const.ADMIN_ID)){
            ShopEntity shopEntity = shopService.get(shopId);
            userId = shopEntity.getUserId();
        }
        List<MallGoodsEntity> mallGoodsEntity = mallGoodsService.findByUserId(userId,MallGoodsShelfEnum.ON.getIndex());
        return R.ok(mallGoodsEntity);
    }
}
